package com.maruping.disk.user.control;

import com.alibaba.fastjson.JSON;
import com.maruping.disk.mybatis.entity.PtUserEntity;
import com.maruping.disk.mybatis.flexigrid.PagingEntity;
import com.maruping.disk.mybatis.flexigrid.TblResponseEntity;
import com.maruping.disk.mybatis.ztree.ZtreeEntity;
import com.maruping.disk.spring.control.BaseController;
import com.maruping.disk.spring.security.UserDiskEntity;
import com.maruping.disk.user.entity.SearchUserEntity;
import com.maruping.disk.user.exception.EmailRepeatException;
import com.maruping.disk.user.exception.MobileRepeatException;
import com.maruping.disk.user.exception.UserNameRepeatException;
import com.maruping.disk.user.exception.UserOccupyException;
import com.maruping.disk.user.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
    @Resource
    private UserService userService;

    @RequestMapping("/queryUserList")
    @ResponseBody
    public List<PtUserEntity> queryUserList(){
        List<PtUserEntity> list = userService.queryUserList();
        return  list;
    }
    @Secured("ROLE_cldk_data_user_del")
    @RequestMapping("/deleteUserByIds")
    @ResponseBody
    public String deleteUserByIds(@RequestParam("ids") String ids){
        try {
            userService.deleteUserByIds(ids);
        } catch (UserOccupyException e) {
            return failJson("user.delete.fail",e.getMessage());
        }
        return successJson("user.delete.success");
    }
    @Secured("ROLE_cldk_data_user")
    @RequestMapping("/userPage")
    public String userPage(){
        return "user/userPage";
    }

    @RequestMapping("/queryUserInfoListByPage")
    @ResponseBody
    public String queryUserInfoListByPage(SearchUserEntity entity, PagingEntity paging){
        TblResponseEntity<PtUserEntity> responseEntity = userService.queryUserInfoListByPage(entity,paging);

        return JSON.toJSONString(responseEntity);
    }

    @Secured("ROLE_cldk_data_user")
    @RequestMapping("/queryUserInfoById")
    @ResponseBody
    public String queryUserInfoById(@RequestParam("userUuid") String userUuid){
        PtUserEntity entity = userService.queryUserInfoById(userUuid);
        return JSON.toJSONString(entity);
    }
    @Secured("ROLE_cldk_data_user_mod")
    @RequestMapping("/modifyUserInfoById")
    @ResponseBody
    public String modifyUserInfoById(PtUserEntity entity){
        try {
            userService.modifyUserInfoById(entity);
        } catch (EmailRepeatException e) {
            return failJson("user.email.repeat");
        } catch (MobileRepeatException e) {
            return failJson("user.mobile.repeat");
        } catch (UserNameRepeatException e) {
            return failJson("user.name.repeat");
        }
        return successJson("user.modify.success");
    }
    @Secured("ROLE_cldk_data_user_add")
    @RequestMapping("/addUserInfo")
    @ResponseBody
    public String addUserInfo(PtUserEntity entity){
        try {
            userService.addUserInfo(entity);
        } catch (EmailRepeatException e) {
            return failJson("user.email.repeat");
        } catch (MobileRepeatException e) {
            return failJson("user.mobile.repeat");
        } catch (UserNameRepeatException e) {
            return failJson("user.name.repeat");
        }
        return successJson("user.add.success");
    }
    @Secured("ROLE_cldk_data_user_role")
    @RequestMapping("/queryRoleTreeListByUser")
    @ResponseBody
    public String queryRoleTreeListByUser(@Param("userUuid") String userUuid){
        List<ZtreeEntity> list = userService.queryRoleTreeListByUser(userUuid);
        return JSON.toJSONString(list);
    }
    @Secured("ROLE_cldk_data_user_role")
    @RequestMapping("/saveRoleRefUser")
    @ResponseBody
    public String saveRoleRefUser(@Param("userUuidArray") String userUuidArray,@Param("roleUuidArray") String roleUuidArray){
        userService.saveRoleRefUser(userUuidArray,roleUuidArray);
        return successJson("user.allocat.role.success");
    }

    @Secured("ROLE_cldk_data_user_reset")
    @PostMapping("/resetPassword")
    @ResponseBody
    public String resetPassword(@RequestParam("userUuids") String userUuids) {
        try {
            userService.resetPasswords(userUuids);
            return successJson("user.password.reset.success");
        } catch (Exception e) {
            return failJson("user.password.reset.fail");
        }
    }


    /**
     * 修改当前用户密码
     */
    @Secured("ROLE_cldk_data_user_mod")
    @PostMapping("/changePassword")
    @ResponseBody
    public String changePassword(
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            @RequestParam String confirmPassword) {

        // 验证新密码和确认密码是否一致
        if(!newPassword.equals(confirmPassword)) {
            return failJson("user.password.not.match");
        }

        // 获取当前登录用户
        UserDiskEntity currentUser = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        try {
            // 创建用户实体并设置新密码
            PtUserEntity userEntity = new PtUserEntity();
            userEntity.setUserUuid(currentUser.getUserUuid());
            userEntity.setPassword(newPassword); // 密码会在service层加密

            // 调用修改方法（会验证旧密码）
            userService.changePassword(userEntity, oldPassword);

            return successJson("user.password.change.success");
        } catch (Exception e) {
            return failJson("user.password.change.fail",e.getMessage());
        }
    }


}